from flask import Blueprint, request, jsonify
from app import mysql
import re
import random

auth_bp = Blueprint('users', __name__)

def generate_account():
    length = random.randint(6, 9)
    return ''.join([str(random.randint(0, 9)) for _ in range(length)])

@auth_bp.route('/users/register', methods=['POST'])
def register():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')

    # 验证输入
    if not username or not password:
        return jsonify({'success': False, 'message': '用户名和密码不能为空'}), 400
    
    if len(username) < 4 or len(username) > 16:
        return jsonify({'success': False, 'message': '用户名需4-16位字符'}), 400
    
    if len(password) < 8:
        return jsonify({'success': False, 'message': '密码至少需要8位'}), 400

    cursor = mysql.connection.cursor()
    try:
        # 查重
        cursor.execute("SELECT * FROM users WHERE username = %s", (username,))
        if cursor.fetchone():
            return jsonify({'success': False, 'message': '用户名已存在'}), 400

        # 生成唯一账号
        def insert_user_with_unique_account():
            account = generate_account()
            cursor.execute("SELECT * FROM users WHERE account = %s", (account,))
            if cursor.fetchone():
                return insert_user_with_unique_account()
            cursor.execute(
                "INSERT INTO users (username, password, account) VALUES (%s, %s, %s)",
                (username, password, account)
            )
            mysql.connection.commit()
            return jsonify({
                'success': True,
                'message': '注册成功',
                'user': {
                    'username': username,
                    'account': account
                }
            })
        return insert_user_with_unique_account()
    except Exception as e:
        mysql.connection.rollback()
        return jsonify({'success': False, 'message': str(e)}), 500
    finally:
        cursor.close()

@auth_bp.route('/users/login', methods=['POST'])
def login():
    data = request.get_json()
    account = data.get('account')
    password = data.get('password')

    cursor = mysql.connection.cursor()
    cursor.execute(
        "SELECT * FROM users WHERE account = %s AND password = %s",
        (account, password)
    )
    user = cursor.fetchone()
    cursor.close()

    if user:
        return jsonify({
            'success': True,
            'message': '登录成功',
            'user': {
                'username': user['username'],
                'account': user['account']
            }
        })
    else:
        return jsonify({'success': False, 'message': '账号或密码错误'}), 401
